package floappcontest.core.backbeans;

import floappcontest.core.beans.FloappSession;
import floappcontest.core.beans.User;
import floappcontest.core.beans.UserType;
import floappcontest.core.control.Control;
import floappcontest.core.dao.factory.HibernateDAOFactory;
import floappcontest.core.exception.FloAppException;


/**
 * Managed bean which performs the administrator setup operation. When the
 * contest is run for the first time, the user is asked to crate an
 * administrator user. This bean performs this operation registering the user in
 * the database and bind it to the current session.
 */
public class AdminSetUp {

	private static final String ADMIN_LOGIN = "admin"; //$NON-NLS-1$
	private static final String FAILED = "FAILED"; //$NON-NLS-1$
	private static final String OK = "OK"; //$NON-NLS-1$
	private User user;
	private Control control;


	/**
	 * Default empty constructor. 
	 */
	public AdminSetUp() {
		setUser( new User() );
		setControl( new Control( new HibernateDAOFactory() ) );
	}


	/**
	 * Observer method of the attribute user.
	 * @return The user which will be inserted into the database.
	 */
	public User getUser() {
		return this.user;
	}


	/**
	 * Private observer method of the private attribute control.
	 * @return The control of the application.
	 */
	private Control getControl() {
		return this.control;
	}


	/**
	 * Mutator method of the attribute user.
	 * @param user The new user to be inserted into the database.
	 */
	public void setUser( User user ) {
		this.user = user;
	}


	/**
	 * Private mutator method of the attribute user.
	 * @param control The control of the application.
	 */
	private void setControl( Control control ) {
		this.control = control;
	}


	/**
	 * Operation performed to insert the administrator user into the database.
	 * @return String signal to JSF navigation rules. 
	 */
	public String insert() {
		try {
			getUser().setLogin( ADMIN_LOGIN );
			getUser().setType( UserType.ADMINISTRATOR );
			getControl().insertUser( getUser() );
			FloappSession.bind( getUser(), UserType.ADMINISTRATOR );
			setUser( new User() );
			return OK;
		} catch ( FloAppException e ) {
			e.printStackTrace();
			setUser( new User() );
			return FAILED;
		}
	}
}